﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using System.Globalization;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.IO;

namespace BSC_OTC_Management.Forms.SoTraiChu  
{
    public partial class Frm_DuyetTTLai : Form
    {
        //variable
        string _formName = "BSC_TBL_TLLOGTTLAI";
        DataTable _tableSTCTTLai = new DataTable("ApprovalTTLai");
        DataTable _tableCoupon = new DataTable("CouponTTLai");
        DataTable _tableViewCoupon = new DataTable("ViewCoupon");
        DataTable _tableViewTLLOGTTLAI = new DataTable("ViewTLLOGTTLAI");
        Code.CL_Ultility _cl = new Code.CL_Ultility();

        public Frm_DuyetTTLai()
        {
            InitializeComponent();
        }

        private void Frm_DuyetTTLai_Load(object sender, EventArgs e)
        {
            //default Enter press
            this.AcceptButton = btn_Search;

            //title huong dan 
            lb_title.Text = "Bạn hãy doubleClick trên bảng Danh sách các Coupon để duyệt thanh toán lãi/gốc.";

            //truy van ten cot cho 2 bang du lieu
            this._tableViewCoupon = _cl._services.GetViewBy_SearchCode("BSC_TBL_COUPON");
            this._tableViewTLLOGTTLAI = _cl._services.GetViewBy_SearchCode("BSC_TBL_TLLOGTTLAI");

            //them su kien mouse down cho gridView2
            this.gridView2.DoubleClick += new System.EventHandler(this.gridView2_DoubleClick);
        }

        private void Load_Coupon()
        {
            try
            {
                string ngayttlai = DateTime.ParseExact(dt_ngayttlai.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
                string tentp = txtTraiphieuphathanh.Text;
                string condition = "";

                condition = " and a.ngayttlai <= TO_DATE('" + ngayttlai + "','dd/MM/yyyy')" +
                            " and Upper(b.tentp) like '%" + tentp.ToUpper() + "%'" +
                            " and a.trangthai = 2";

                _tableCoupon = _cl._services.SearchView_BySQL("BSC_TBL_COUPON", condition);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Load_Sotraichu_TTLai(string _macoupon)
        {
            try
            {
                //command text
                string sql = "Select tl.macoupon, tl.matp, tl.makh, tl.maso, tl.matk, ac.cdcontent thanhtoangoc, st.slphothong, st.slhanche, st.slcamco,tl.tienlai,tl.tlphongtoa,tl.tiengoc,tl.tgphongtoa,tl.tong,al.cdcontent trangthaicoupon, "
                            + "f.tlname last_changeid "
                            + "from bsc_tbl_tllogttlai tl, bsc_tbl_sotraichu st, allcode al, allcode ac,tlprofiles f "
                            + "where tl.trangthaicoupon = al.cdval and tl.thanhtoangoc = ac.cdval "
                            + "and  tl.maso = st.maso "
                            + "and f.tlid(+) = tl.last_changeid "
                            + "and al.cdname = 'TRANGTHAI' and al.cdtype = 'BSC_TBL_COUPON' "
                            + "and ac.cdname = 'THANHTOANGOC' and ac.cdtype = 'BSC_TBL_COUPON' "
                            + "and tl.trangthaicoupon = 2 "
                            + "and tl.macoupon ='" + _macoupon + "'"; 
                _tableSTCTTLai = _cl._services.GetDatatable_BySQL(sql);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        #region Event
        private void btn_Approve_Click(object sender, EventArgs e)
        {
            try
            {

                if (CheckDieuKien())
                {
                    if (QuestionDialog(Code.StaticVariable.messeseboxDuyetTTLai + value.ToString()))
                    {
                        //lấy thông tin duyệt
                        string sql = "select autoid ,macoupon ,matp,makh,maso ,matk ,thanhtoangoc,tienlai,tlphongtoa,tiengoc,tgphongtoa,tong "
                                   + "from bsc_tbl_tllogttlai where macoupon ='" + value.ToString() + "' and trangthaicoupon = 2";
                        DataTable _logTA = new DataTable("tllogttlai");
                        _logTA = _cl._services.GetDatatable_BySQL(sql);
                        //_logTA.Columns.Remove("trangthaicoupon");

                        //duyệt từng bản ghi
                        DataTable noname = new DataTable("noname");
                        foreach (DataColumn col in _logTA.Columns)
                        {
                            noname.Columns.Add(col.ColumnName, typeof(String));
                        }

                        if (_logTA.Rows.Count > 0)
                        {
                            for (int i = 0; i < _logTA.Rows.Count; i++)
                            {
                                //xoá bản ghi cũ
                                noname.Clear();
                                //create new row
                                DataRow rowValue = noname.NewRow();
                                DataRow rowType = noname.NewRow();

                                //add value to row
                                for (int j = 0; j < noname.Columns.Count; j++)
                                {
                                    rowValue[j] = _logTA.Rows[i][j];
                                    if (_logTA.Columns[j].DataType == typeof(DateTime))
                                        rowType[j] = "D";
                                    else
                                        rowType[j] = "T";

                                }
                                noname.Rows.Add(rowValue);
                                noname.Rows.Add(rowType);
                                //noname.Rows.Add(_logTA.Rows[i].ItemArray);
                                string store = "bsc_201.Approval_tt_lai_goc";
                                string _result = _cl._services.Excute_Store_Transaction(store, noname);
                                if (_result != "0")
                                    throw new Exception(_result);
                            }
                        }

                        //luu vet nguoi thuc hien
                        _cl._services.Update_Last_Approve(_formName, "MACOUPON", value.ToString(), Code.StaticVariable.userID);

                        //Update_Coupon_Status
                        if (_cl._services.Update_Coupon_Status(value.ToString(), 1))//1:da thanh toan coupon
                        {
                            MessageBox.Show(Code.StaticVariable.messeseboxThanhCong, Code.StaticVariable.messeseboxLuuY);
                            _cl.ClearAllText(this);
                            btn_Search_Click(sender, e);
                            this.gridControl1.DataSource = null;
                            this.gridControl1.Refresh();
                            return;
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btt_Cancel_Click(object sender, EventArgs e)
        {

            this.Close();
        }

        private void btn_Search_Click(object sender, EventArgs e)
        {
            //load danh sach coupon theo ngayttlai va ten trai phieu
            Load_Coupon();

            //hien thi ten cot theo tieng viet
            LoadDataGrid(_tableCoupon, _tableViewCoupon, this.gridControl2, this.gridView2);
        }

        //khai báo đối tượng cho row
        object value = null;
        private void gridView2_DoubleClick(object sender, EventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
            Point p = view.GridControl.PointToClient(Control.MousePosition);
            GridHitInfo hi = gridView2.CalcHitInfo(p);
            if (hi.InRowCell)
            {
                value = gridView2.GetRowCellValue(hi.RowHandle, "MACOUPON");
                if (value != null)
                {
                    //load thong tin so dang thanh toan
                    Load_Sotraichu_TTLai(value.ToString());
                    //thay ten cot
                    LoadDataGrid(_tableSTCTTLai, _tableViewTLLOGTTLAI, this.gridControl1, this.gridView1);
                }
            }
        }

        #endregion Event

        #region ham xu ly
        private bool CheckDieuKien()
        {
            if (this.value == null)
            {
                MessageBox.Show("Bạn phải chọn một Coupon đến hạn cần tính lãi/gốc", Code.StaticVariable.messeseboxLuuY);
                return false;
            }
            return true;
        }

        private bool QuestionDialog(string _caption)
        {
            DialogResult result = MessageBox.Show(_caption + " ?", Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.OKCancel);
            if (result == DialogResult.OK)
                return true;
            else
                return false;
        }

        //_dt bang nguon, _tableView bang du lieu ten cot
        private void LoadDataGrid(DataTable _dt, DataTable _tableView, DevExpress.XtraGrid.GridControl gridControl,DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {
            try
            {
                bool duyet = false;
                DataTable view = new DataTable("View");
                foreach (DataColumn col in _dt.Columns)
                {
                    if (col.ColumnName == "DUYET")
                    {
                        duyet = true;
                        view.Columns.Add(col.ColumnName, typeof(String));
                    }
                    else
                        view.Columns.Add(col.ColumnName, col.DataType);
                }

                for (int i = 0; i < _dt.Rows.Count; i++)
                {
                    view.Rows.Add(_dt.Rows[i].ItemArray);
                }

                //add duyet
                if (duyet)
                {
                    DataTable tblduyet = new DataTable("Duyet");
                    tblduyet = _cl._services.GetDatatable_BySQL("select * from allcode where cdtype = 'AP' and cdname = 'DUYET' and cduser='Y' ORDER BY lstodr");
                    for (int i = 0; i < view.Rows.Count; i++)
                    {
                        for (int j = 0; j < tblduyet.Rows.Count; j++)
                        {
                            if (view.Rows[i]["DUYET"].ToString() == tblduyet.Rows[j]["CDVAL"].ToString())
                                view.Rows[i]["DUYET"] = tblduyet.Rows[j]["CDCONTENT"];
                        }
                    }
                }

                // Thay tên dựa theo FieldCode, FieldName
                gridControl.DataSource = view;

                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                {

                    //thay ten column
                    foreach (DataRow row in _tableView.Rows)
                    {
                        if (row["fldname"].ToString().ToUpper() == column.ToString())
                        {
                            gridView.Columns[column.ToString()].Caption = row["caption"].ToString(); ;
                        }
                    }

                    //dinh dang truong so cho cell
                    if (column.ColumnType == typeof(System.Decimal))
                    {
                        column.DisplayFormat.FormatType = FormatType.Numeric;
                        column.DisplayFormat.FormatString = "#,##0.###";
                    }
                }

                gridView.BestFitColumns();
                //datnt: dont edit any cell in gridView
                gridView.OptionsBehavior.Editable = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Code.StaticVariable.messeseboxLuuY);
            }
        }
        #endregion

        private void btn_Export_Click(object sender, EventArgs e)
        {
            if (this.gridView1.RowCount >0)
            {
                using (SaveFileDialog saveDialog = new SaveFileDialog())
                {
                    saveDialog.Filter = "Excel (2003)(.xls)|*.xls|Excel (2010) (.xlsx)|*.xlsx |Pdf File (.pdf)|*.pdf |Html File (.html)|*.html";
                    if (saveDialog.ShowDialog() != DialogResult.Cancel)
                    {
                        string exportFilePath = saveDialog.FileName;
                        string fileExtenstion = new FileInfo(exportFilePath).Extension;

                        switch (fileExtenstion)
                        {
                            case ".xls":
                                gridControl1.ExportToXls(exportFilePath);
                                break;
                            case ".xlsx":
                                gridControl1.ExportToXlsx(exportFilePath);
                                break;
                            case ".pdf":
                                gridControl1.ExportToPdf(exportFilePath);
                                break;
                            case ".html":
                                gridControl1.ExportToHtml(exportFilePath);
                                break;
                            default:
                                break;
                        }

                        if (File.Exists(exportFilePath))
                        {
                            try
                            {
                                //Try to open the file and let windows decide how to open it.
                                System.Diagnostics.Process.Start(exportFilePath);
                            }
                            catch
                            {
                                String msg = "File không thể mở." + Environment.NewLine + Environment.NewLine + "Path: " + exportFilePath;
                                MessageBox.Show(msg, Code.StaticVariable.messeseboxLuuY);
                            }
                        }
                        else
                        {
                            String msg = "File không thể lưu trữ." + Environment.NewLine + Environment.NewLine + "Path: " + exportFilePath;
                            MessageBox.Show(msg, Code.StaticVariable.messeseboxLuuY);
                        }
                    }
                }
            }
        }

        private void btn_Reject_Click(object sender, EventArgs e)
        {
            if (QuestionDialog("Bạn từ chối duyệt coupon "+ value.ToString()))
            {
                //delete all rows which have macoupon = this value in bsc_tbl_tllogttlai?
                if (!_cl._services.Excute_DB("delete bsc_tbl_tllogttlai where macoupon = " + value.ToString()))
                    return;

                //update status of coupon in bsc_tbl_coupon 2 -> 0
                if (_cl._services.Update_Coupon_Status(value.ToString(), 0))//0: chua thanh toan
                {
                    MessageBox.Show(Code.StaticVariable.messeseboxThanhCong, Code.StaticVariable.messeseboxLuuY);
                    _cl.ClearAllText(this);
                    btn_Search_Click(sender, e);
                    this.gridControl1.DataSource = null;
                    this.gridControl1.Refresh();
                    return;
                }
            }
        }

    }
}
